package pc;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.HashMap;

import lejos.pc.comm.NXTComm;
import lejos.pc.comm.NXTCommException;
import lejos.pc.comm.NXTCommFactory;
import lejos.pc.comm.NXTInfo;

/*
 * Run with runbtjava script found in project root, like this:
 * cd bin; ../runbtjava pc.Main NXT-1 deadbeef
 */

public class Main {

	/**
	 * @param args
	 * @throws NXTCommException 
	 */
	public static void main(String[] args) throws NXTCommException {
		
		if (args.length != 2) {
			System.out.println("Usage: program <nxt name> <nxt address>");
			System.exit(1);
		}
		
		NXTComm comm = null;
		try {
			comm = NXTCommFactory.createNXTComm(NXTCommFactory.BLUETOOTH);
		} catch (NXTCommException e) {
			System.out.println("Error during BT load");
			System.out.println(e.getMessage());
			System.exit(2);
		}
		
		NXTInfo info = new NXTInfo(args[0], args[1]);
		
		System.out.println("Connected to " + info.name);
		
		NXTInfo[] infos = comm.search(args[0], NXTCommFactory.BLUETOOTH);
		info = infos[0];
		try {
			comm.open(info);
		} catch (NXTCommException e) {
			System.out.println("Exception during open");
			System.out.println(e.getMessage());
			System.exit(2);
		}
		
		DataOutputStream dos = new DataOutputStream(comm.getOutputStream());
		DataInputStream dis = new DataInputStream(comm.getInputStream());
		
		System.out.println("Type 's' to start robot, 'q' to quit.");
		Thread inputhandler = new Thread(new InputHandler(System.in, dos));
		inputhandler.start();
		
		HashMap<Float, Float> coords = new HashMap<Float, Float>();
		float x,y;
		try {
			while (inputhandler.isAlive()) {
				x = dis.readFloat();
				y = dis.readFloat();
				coords.put(x,y);
				System.out.println("Got coordinates: " + x + ", " + y);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			inputhandler.join();
			dis.close();
			dos.close();
			comm.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
